<template>
  <el-dialog v-model="state.visible" width="70%" :title="state.title" :close-on-click-modal="false" draggable>
    <div class="selectTemp">
      <span class="st-title">选择模板：</span>
      <el-select v-model="state.curTemp" style="width: 200px" :disabled="props.readOnly" @change="handleTempChange" placeholder="选择模版">
        <el-option v-for="item in state.tempList" :key="item.value" :value="item.value" :label="item.label">{{ item.label }}</el-option>
      </el-select>
      &nbsp;&nbsp;&nbsp;
      <span class="st-title">选择栏目：</span>
      <el-cascader v-model="state.columnId" :options="state.columnList" :show-all-levels="false" style="width: 200px" />
    </div>
    <el-form ref="dataForm" :model="state.dataForm" :rules="state.ruleValidate" label-width="80px">
      <el-form-item v-for="item in state.formList" :key="item.fieldName" :label="item.name">
        <!-- 输入框 -->
        <template v-if="item.type == '1'">
          <el-input v-model="state.dataForm[item.fieldName]" placeholder="请输入" clearable :disabled="props.readOnly"></el-input>
        </template>
        <!-- 下拉框 -->
        <template v-if="item.type == '3'">
          <el-select v-model="state.dataForm[item.fieldName]" :disabled="props.readOnly">
            <el-option :key="1" :value="1">草稿</el-option>
          </el-select>
        </template>
        <!-- 日期 -->
        <template v-if="item.type == '4'">
          <el-date-picker v-model="state.dataForm[item.fieldName]" type="datetime" :disabled="props.readOnly" value-format="YYYY-MM-DD HH:mm" placeholder="选择日期" @on-change="formatTime($event, item.fieldName)"></el-date-picker>
        </template>
        <!-- 上传封面图 -->
        <template v-if="item.type == '7'">
          <UploadImg :option="state.defaultOption" :img-upload-status="state.imgUploadStatus" :disabled="props.readOnly" @handleImg="handleImg"></UploadImg>
        </template>
        <!-- 上传附件 -->
        <template v-if="item.type == '8'">
          <el-upload style="width: 80%;margin-bottom: 10px;" class="upload-demo" 
          drag v-model:file-list="state.fileList" :headers="headers" :action="baseUrl" 
          :before-upload="beforeUpload" :on-success="handleSuccess" :show-file-list="false">
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">
              将文件拖拽至此 /
              <em>点击上传</em>
            </div>
          </el-upload>
		  <br />
		  <p style="width:80%; margin: 0; display: flex;justify-content: space-between;" v-for="item in state.fileList" :key="item.id">
			<span>{{ item.name }}</span>
			<a style="color: #333;" target="_blank" :href="item?.url" >预览</a>
		  </p>
        </template>
        <!-- 文本域 -->
        <!-- 富文本输入框  -->
        <template v-if="item.type == '2'">
          <wEditor id="eAbs" :item="item" :data="state.dataForm[item.fieldName]" :is-clear="isClear" :height="150" :disabled="props.readOnly" @change="handleChangeWEditor" />
        </template>
      </el-form-item>
      <el-form-item class="el-form-item-footer">
        <el-button type="primary" @click="handleSubmit">保存</el-button>
        <el-button @click="handleCancel">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>
<script setup lang="ts">
import { reactive, ref } from 'vue'
import { ElMessage } from 'element-plus/es'
import { getTemplateListApi, submitColumnApi } from '@/api/cms/template'
import { getArticleInfoApi, submitArticleApi, uploadImgApi } from '@/api/cms/article'
import { getColumnListApi, getColumnTreeApi } from '@/api/cms/column'
import wEditor from '@/components/wEditor.vue'
import UploadImg from '@/components/uploadImg.vue'
const emit = defineEmits(['refreshDataList'])
import { Plus } from '@element-plus/icons-vue'
import { renameObjectProperties } from '@/utils/common.js'
import type { UploadProps } from 'element-plus'
import constant from '@/utils/constant'
import store from '@/store/index.js'

const props = defineProps({
  readOnly: {
    type: Boolean,
    default: false,
  },
})
const baseUrl = (window as any).globalUrl.baseUrl + 'api/cms/files/upload'
const headers = {
  authorization: store.getters['user/token'],
}
const state = reactive({
  fileList: [],
  title: '新增文章',
  uploadFile: '/file/upload',
  visible: false,
  showLoading: false,
  dataForm: {
    id: 0,
    title: '',
    content: '',
    type: 1,
    firstPicture: '',
    files: [],
  },
  imgUploadStatus: false,
  defaultOption: {
    img: '',
  },
  uploadData: {
    file: '',
    params: '',
    fileType: 'CONTENT_COVER_IMAGE',
  },
  ruleValidate: {
    content: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
    title: [{ required: true, message: '标题不能为空', trigger: 'blur' }],
  },
  // 富文本
  isClear: false,
  addRowData: [],
  curTemp: null,
  columnId: '',
  columnList: [], // 选择栏目
  articleId: '', // 文章ID
  originList: [], // 原始模板列表
  tempList: [], // 模板列表
  originInfo: {}, // 文章原始内容
  formList: [], // 每一个模板具体内容
  isReport: false, // 是否是报告
})
const init = (row: any) => {
  state.curTemp = null
  state.formList = []
  state.visible = true
  getTempList()
  getColumnList()
  if (row?.id) {
    state.title = '编辑文章'
    state.articleId = row.id
    getArticleInfo(row)
  } else {
    state.title = '新建文章'
  }
}
//获取模板列表
const getTempList = () => {
  getTemplateListApi({ ips: 100, ipi: 1 }).then((res: any) => {
    const list = res.data.result
    let templist: any = []
    list.forEach((v) => {
      templist.push({
        value: v.id,
        columnId: v.columnId,
        label: v.templateName,
        defaultProperty: v.defaultProperty,
        property: v.property || [],
      })
    })
    state.originList = list
    state.tempList = templist
  })
}
const getColumnList = () => {
  getColumnTreeApi().then((res: any) => {
    let arr = renameObjectProperties(res.data, 'columnName', 'label')
    arr = renameObjectProperties(arr, 'id', 'value')
    state.columnList = renameObjectProperties(arr, 'childColumnDetails', 'children')
  })
}
//更改模板
const handleTempChange = (val: any) => {
  let info = state.originList.find((v) => v.id === val)
  if (!info) {
    return
  }
  //自定义属性
  let attrList = (info && info.property) || []
  attrList.forEach((list) => {
    let attrs = state.dataForm.property
    if (attrs?.length) {
      attrs.forEach((attr) => {
        if (attr.fieldName == list.fieldName) {
          list.value = attr.value
          state.dataForm[list.fieldName] = list.value
        }
      })
    }
  })
  //默认属性
  let defaultList = info.defaultProperty !== '' ? info.defaultProperty : []
  state.formList = defaultList.concat(attrList)
  let copyInfo = JSON.parse(JSON.stringify(info))
  delete copyInfo.defaultProperty
  delete copyInfo.attribute
  state.originInfo = copyInfo
}
const handleCancel = () => {
  state.visible = false
  state.showLoading = false
  state.addRowData = []
  emit('refreshDataList')
}
// 根据id获取详情
const getArticleInfo = (row) => {
  getArticleInfoApi({ id: state.articleId, templateId: row.templateId }).then((res) => {
    if (res) {
      let _data = res.data.content
      state.dataForm = _data
      state.curTemp = Number(_data.templateId)
      state.columnId = _data.columnId
      state.uploadData.params = _data.id
      if (_data.firstPicturePath) {
        state.defaultOption.img = _data.firstPicturePath
      }
      if (state.curTemp) {
        handleTempChange(state.curTemp)
      }
      let list = []
      _data.files.map((item) => {
        list.push({
          name: item.fileShowname,
          url: item.path,
          id: item.id,
          fileSize: item.fileSize,
        })
      })
	  state.fileList = list
    }
  })
}
// 上传裁切封面图
const handleImg = (info) => {
  let file = new File([info], new Date().getTime() + '.png')
  state.uploadData.file = file
  uploadImgApi(state.uploadData).then((res) => {
    state.imgUploadStatus = true
    state.dataForm.firstPicture = res
    ElMessage.success('上传成功')
  })
}
const formatTime = (e, fieldName) => {
  state.dataForm[fieldName] = e
}
const handleChangeWEditor = (obj) => {
  state.dataForm._content = obj.data
}

//上传附件
const handleSuccess: UploadProps['onSuccess'] = (res, file) => {
  if (res.status !== 200) {
    ElMessage.error('上传失败：' + res.msg)
    return false
  } else {
    console.log('---', state.fileList)
    ElMessage.success('上传成功')
  }
}
const beforeUpload: UploadProps['beforeUpload'] = (file) => {
  if (file.size / 1024 / 1024 / 1024 / 1024 > 1) {
    ElMessage.error('文件大小不能超过100M')
    return false
  }
  return true
}

//提交
const handleSubmit = () => {
  state.showLoading = true
  let param = {}
  param = state.originInfo
  param.attribute = []
  let list = [
    'title',
    'author',
    'titleImgUrl',
    'firstPicture',
    'from',
    'url',
    'key',
    'source',
    'sourceUrl',
    'files',
    'keyword',
    'content',
    '_content', // 这里的_content为content的临时变量，从wEditor里获取
    'issuedTime',
  ]
  for (let item in state.dataForm) {
    // 默认属性
    if (list.indexOf(item) > -1) {
      param[item] = state.dataForm[item]
    } else {
      //自定属性
      let obj = (state.originInfo.property && state.originInfo.property.find((attr) => attr.fieldName == item)) || {}
      if (obj && Object.keys(obj).length > 0) {
        obj.value = state.dataForm[item]
        param.attribute.push(obj)
      }
    }
  }
  param.templateId = param.id
  param.id = state.articleId
  param['content'] = param['_content']
  param['property'] = param['attribute']
  delete param._content
  delete param.name
  delete param.attribute
  delete param.createTime
  delete param.creater
  param['files'] = []
  //处理附件
  state.fileList.map((item) => {
	let id =  item?.response?.data || item?.id
	param['files'].push(id)
  })
  submitArticleApi(param).then((res) => {
    state.showLoading = false
    if (res) {
      state.visible = false
      ElMessage.success({
        content: '操作成功',
        duration: 2,
        onClose: () => {
          handleCancel()
          emit('refreshDataList')
        },
      })
    } else {
      ElMessage.error(res.data.message)
    }
  })
}

defineExpose({
  init,
})
</script>
<style scoped lang="scss">
.selectTemp {
  margin-bottom: 20px;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
.el-form-item-footer .el-form-item__content {
  display: flex;
  justify-content: flex-end;
}
</style>
